#include "console_backend.h"

#include "sfc/io.h"

namespace sfc::log {

ConsoleBackend::ConsoleBackend() {
  auto& stdout = io::Stdout::instance();
  _enable_color = stdout.is_tty();
}

ConsoleBackend::ConsoleBackend(ConsoleBackend&&) noexcept = default;

ConsoleBackend::~ConsoleBackend() {}

void ConsoleBackend::set_color(bool value) {
  _enable_color = value;
}

void ConsoleBackend::flush() {
  static auto& imp = io::Stdout::instance();
  imp.flush();
}

void ConsoleBackend::write_entry(Entry entry) {
  static const Str LEVEL_STR[] = {"VB", "DE", "II ", "WW ", "EE", "FA", "??"};
  static const Str COLOR_STR[] = {"39", "32", "34", "33", "31", "41", ""};

  static thread_local auto buf = String{};
  buf.clear();
  if (!_enable_color) {
    fmt::write(buf, "{} [{}] {}\n", entry.time, LEVEL_STR[(u32)(entry.level)], entry.msg);
  } else {
    fmt::write(buf, "\033[{}m{}\033[39;49m {}\n", COLOR_STR[(u32)entry.level], entry.time,
               entry.msg);
  }

  static auto& imp = io::Stdout::instance();
  imp.write_str(buf.as_str());
}

}  // namespace sfc::log
